<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>小程序之自定义组件 | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="小程序,">
  

  <meta name="description" content="一、创建自定义组件 类似于页面，一个自定义组件由 json wxml wxss js 4个文件组成。要编写一个自定义组件，首先需要在 json 文件中进行自定义组件声明（将 component 字段设为 true 可这一组文件设为自定义组件）  &amp;#123;  &amp;quot;component&amp;quot;: true&amp;#125; 二、使用自定义组件 使用已注册的自定义组件前，首先要在页面的 json">
<meta name="keywords" content="小程序">
<meta property="og:type" content="article">
<meta property="og:title" content="小程序之自定义组件">
<meta property="og:url" content="http://blog.poetries.top/2018/08/12/wx-component/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="一、创建自定义组件 类似于页面，一个自定义组件由 json wxml wxss js 4个文件组成。要编写一个自定义组件，首先需要在 json 文件中进行自定义组件声明（将 component 字段设为 true 可这一组文件设为自定义组件）  &amp;#123;  &amp;quot;component&amp;quot;: true&amp;#125; 二、使用自定义组件 使用已注册的自定义组件前，首先要在页面的 json">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2018/3/14/16223cc683fa5afc?w=295&h=676&f=png&s=15505">
<meta property="og:updated_time" content="2020-08-15T04:25:31.942Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="小程序之自定义组件">
<meta name="twitter:description" content="一、创建自定义组件 类似于页面，一个自定义组件由 json wxml wxss js 4个文件组成。要编写一个自定义组件，首先需要在 json 文件中进行自定义组件声明（将 component 字段设为 true 可这一组文件设为自定义组件）  &amp;#123;  &amp;quot;component&amp;quot;: true&amp;#125; 二、使用自定义组件 使用已注册的自定义组件前，首先要在页面的 json">
<meta name="twitter:image" content="https://user-gold-cdn.xitu.io/2018/3/14/16223cc683fa5afc?w=295&h=676&f=png&s=15505">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#一、创建自定义组件"><span class="toc-text">一、创建自定义组件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#二、使用自定义组件"><span class="toc-text">二、使用自定义组件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#三、组件模版"><span class="toc-text">三、组件模版</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#四、Component构造器"><span class="toc-text">四、Component构造器</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#五、组件间通信与事件"><span class="toc-text">五、组件间通信与事件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#六、自定义组件案例"><span class="toc-text">六、自定义组件案例</span></a></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-wx-component" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">小程序之自定义组件</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2018.08.12</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/Front-End/">Front-End</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 2.1k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 9分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <h2 id="一、创建自定义组件"><a href="#一、创建自定义组件" class="headerlink" title="一、创建自定义组件"></a>一、创建自定义组件</h2><blockquote>
<p>类似于页面，一个自定义组件由 <code>json</code> <code>wxml</code> <code>wxss</code> <code>js</code> 4个文件组成。要编写一个自定义组件，首先需要在 json 文件中进行自定义组件声明（将 component 字段设为 true 可这一组文件设为自定义组件）</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  &quot;component&quot;: true</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="二、使用自定义组件"><a href="#二、使用自定义组件" class="headerlink" title="二、使用自定义组件"></a>二、使用自定义组件</h2><blockquote>
<p>使用已注册的自定义组件前，首先要在页面的 json 文件中进行引用声明。此时需要提供每个自定义组件的标签名和对应的自定义组件文件路径</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="string">"usingComponents"</span>: &#123;</span><br><span class="line">    <span class="string">"component-tag-name"</span>: <span class="string">"path/to/the/custom/component"</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>这样，在页面的 wxml 中就可以像使用基础组件一样使用自定义组件。节点名即自定义组件的标签名，节点属性即传递给组件的属性值。</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&lt;view&gt;</span><br><span class="line">  &lt;!-- 以下是对一个自定义组件的引用 --&gt;</span><br><span class="line">  &lt;component-tag-name inner-text=&quot;Some text&quot;&gt;&lt;/component-tag-name&gt;</span><br><span class="line">&lt;/view&gt;</span><br></pre></td></tr></table></figure>
<h2 id="三、组件模版"><a href="#三、组件模版" class="headerlink" title="三、组件模版"></a>三、组件模版</h2><ul>
<li>在组件模板中可以提供一个 <code>&lt;slot&gt;</code>节点，用于承载组件引用时提供的子节点</li>
</ul>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 组件模板 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">view</span> <span class="attr">class</span>=<span class="string">"wrapper"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">view</span>&gt;</span>这里是组件的内部节点<span class="tag">&lt;/<span class="name">view</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">slot</span>&gt;</span><span class="tag">&lt;/<span class="name">slot</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">view</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 引用组件的页面模版 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">view</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">component-tag-name</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 这部分内容将被放置在组件 &lt;slot&gt; 的位置上 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">view</span>&gt;</span>这里是插入到组件slot中的内容<span class="tag">&lt;/<span class="name">view</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">component-tag-name</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">view</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>模版数据绑定</strong></p>
<blockquote>
<p>可以使用数据绑定，这样就可以向子组件的属性传递动态数据</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 引用组件的页面模版 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">view</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">component-tag-name</span> <span class="attr">prop-a</span>=<span class="string">"&#123;&#123;dataFieldA&#125;&#125;"</span> <span class="attr">prop-b</span>=<span class="string">"&#123;&#123;dataFieldB&#125;&#125;"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 这部分内容将被放置在组件 &lt;slot&gt; 的位置上 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">view</span>&gt;</span>这里是插入到组件slot中的内容<span class="tag">&lt;/<span class="name">view</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">component-tag-name</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">view</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>组件wxml的slot</strong></p>
<ul>
<li>在组件的<code>wxml</code>中可以包含 <code>slot</code> 节点，用于承载组件使用者提供的<code>wxml</code>结构。</li>
<li>默认情况下，一个组件的<code>wxml</code>中只能有一个<code>slot</code>。需要使用多<code>slot</code>时，可以在组件js中声明启用</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">Component(&#123;</span><br><span class="line">  options: &#123;</span><br><span class="line">    multipleSlots: <span class="literal">true</span> <span class="comment">// 在组件定义时的选项中启用多slot支持</span></span><br><span class="line">  &#125;,</span><br><span class="line">  properties: &#123; <span class="comment">/* ... */</span> &#125;,</span><br><span class="line">  methods: &#123; <span class="comment">/* ... */</span> &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>此时，可以在这个组件的wxml中使用多个slot，以不同的 name 来区分</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 组件模板 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">view</span> <span class="attr">class</span>=<span class="string">"wrapper"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">slot</span> <span class="attr">name</span>=<span class="string">"before"</span>&gt;</span><span class="tag">&lt;/<span class="name">slot</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">view</span>&gt;</span>这里是组件的内部细节<span class="tag">&lt;/<span class="name">view</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">slot</span> <span class="attr">name</span>=<span class="string">"after"</span>&gt;</span><span class="tag">&lt;/<span class="name">slot</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">view</span>&gt;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>使用时，用 slot 属性来将节点插入到不同的slot上</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 引用组件的页面模版 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">view</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">component-tag-name</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 这部分内容将被放置在组件 &lt;slot name="before"&gt; 的位置上 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">view</span> <span class="attr">slot</span>=<span class="string">"before"</span>&gt;</span>这里是插入到组件slot name="before"中的内容<span class="tag">&lt;/<span class="name">view</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 这部分内容将被放置在组件 &lt;slot name="after"&gt; 的位置上 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">view</span> <span class="attr">slot</span>=<span class="string">"after"</span>&gt;</span>这里是插入到组件slot name="after"中的内容<span class="tag">&lt;/<span class="name">view</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">component-tag-name</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">view</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="四、Component构造器"><a href="#四、Component构造器" class="headerlink" title="四、Component构造器"></a>四、Component构造器</h2><blockquote>
<p>Component构造器可用于定义组件，调用Component构造器时可以指定组件的属性、数据、方法等</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">Component(&#123;</span><br><span class="line"></span><br><span class="line">  behaviors: [],</span><br><span class="line"></span><br><span class="line">  properties: &#123;</span><br><span class="line">    myProperty: &#123; <span class="comment">// 属性名</span></span><br><span class="line">      type: <span class="built_in">String</span>, <span class="comment">// 类型（必填），目前接受的类型包括：String, Number, Boolean, Object, Array, null（表示任意类型）</span></span><br><span class="line">      value: <span class="string">''</span>, <span class="comment">// 属性初始值（可选），如果未指定则会根据类型选择一个</span></span><br><span class="line">      observer: <span class="function"><span class="keyword">function</span>(<span class="params">newVal, oldVal, changedPath</span>) </span>&#123;</span><br><span class="line">         <span class="comment">// 属性被改变时执行的函数（可选），也可以写成在methods段中定义的方法名字符串, 如：'_propertyChange'</span></span><br><span class="line">         <span class="comment">// 通常 newVal 就是新设置的数据， oldVal 是旧数据</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    myProperty2: <span class="built_in">String</span> <span class="comment">// 简化的定义方式</span></span><br><span class="line">  &#125;,</span><br><span class="line">  data: &#123;&#125;, <span class="comment">// 私有数据，可用于模版渲染</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// 生命周期函数，可以为函数，或一个在methods段中定义的方法名</span></span><br><span class="line">  attached: <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;,</span><br><span class="line">  moved: <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;,</span><br><span class="line">  detached: <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;,</span><br><span class="line"></span><br><span class="line">  methods: &#123;</span><br><span class="line">    onMyButtonTap: <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">      <span class="keyword">this</span>.setData(&#123;</span><br><span class="line">        <span class="comment">// 更新属性和数据的方法与更新页面数据的方法类似</span></span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">// 内部方法建议以下划线开头</span></span><br><span class="line">    _myPrivateMethod: <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">      <span class="comment">// 这里将 data.A[0].B 设为 'myPrivateData'</span></span><br><span class="line">      <span class="keyword">this</span>.setData(&#123;</span><br><span class="line">        <span class="string">'A[0].B'</span>: <span class="string">'myPrivateData'</span></span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;,</span><br><span class="line">    _propertyChange: <span class="function"><span class="keyword">function</span>(<span class="params">newVal, oldVal</span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<ul>
<li>在 properties 定义段中，属性名采用驼峰写法（propertyName）；</li>
<li>在 wxml 中，指定属性值时则对应使用连字符写法（<code>component-tag-name property-name=&quot;attr value&quot;</code>），应用于数据绑定时采用驼峰写法（<code>attr=&quot;&quot;</code>）</li>
</ul>
<h2 id="五、组件间通信与事件"><a href="#五、组件间通信与事件" class="headerlink" title="五、组件间通信与事件"></a>五、组件间通信与事件</h2><p><strong>组件间通信</strong></p>
<blockquote>
<p>组件间的基本通信方式有以下几种。</p>
</blockquote>
<ul>
<li>WXML 数据绑定：用于父组件向子组件的指定属性设置数据</li>
<li>事件：用于子组件向父组件传递数据，可以传递任意数据。</li>
<li>如果以上两种方式不足以满足需要，父组件还可以通过 <code>this.selectComponent</code> 方法获取子组件实例对象，这样就可以直接访问组件的任意数据和方法</li>
</ul>
<p><strong>监听事件</strong></p>
<ul>
<li>自定义组件可以触发任意的事件，引用组件的页面可以监听这些事件</li>
<li>监听自定义组件事件的方法与监听基础组件事件的方法完全一致</li>
</ul>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 当自定义组件触发“myevent”事件时，调用“onMyEvent”方法 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">component-tag-name</span> <span class="attr">bindmyevent</span>=<span class="string">"onMyEvent"</span> /&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 或者可以写成 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">component-tag-name</span> <span class="attr">bind:myevent</span>=<span class="string">"onMyEvent"</span> /&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">Page(&#123;</span><br><span class="line">  onMyEvent: <span class="function"><span class="keyword">function</span>(<span class="params">e</span>)</span>&#123;</span><br><span class="line">    e.detail <span class="comment">// 自定义组件触发事件时提供的detail对象</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p><strong>触发事件</strong></p>
<blockquote>
<p>自定义组件触发事件时，需要使用 <code>triggerEvent</code> 方法，指定事件名、<code>detail</code>对象和事件选项</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 在自定义组件中 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">bindtap</span>=<span class="string">"onTap"</span>&gt;</span>点击这个按钮将触发“myevent”事件<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">Component(&#123;</span><br><span class="line">  properties: &#123;&#125;</span><br><span class="line">  methods: &#123;</span><br><span class="line">    onTap: <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">      <span class="keyword">var</span> myEventDetail = &#123;&#125; <span class="comment">// detail对象，提供给事件监听函数</span></span><br><span class="line">      <span class="keyword">var</span> myEventOption = &#123;&#125; <span class="comment">// 触发事件的选项</span></span><br><span class="line">      <span class="keyword">this</span>.triggerEvent(<span class="string">'myevent'</span>, myEventDetail, myEventOption)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h2 id="六、自定义组件案例"><a href="#六、自定义组件案例" class="headerlink" title="六、自定义组件案例"></a>六、自定义组件案例</h2><blockquote>
<p>实现一个弹框</p>
</blockquote>
<ul>
<li>在component下新建popup文件夹</li>
</ul>
<p><img src="https://user-gold-cdn.xitu.io/2018/3/14/16223cc683fa5afc?w=295&amp;h=676&amp;f=png&amp;s=15505" alt></p>
<p>popup.wxml</p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">view</span> <span class="attr">class</span>=<span class="string">"wx-popup"</span> <span class="attr">hidden</span>=<span class="string">"&#123;&#123;flag&#125;&#125;"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">view</span> <span class="attr">class</span>=<span class="string">'popup-container'</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">view</span> <span class="attr">class</span>=<span class="string">"wx-popup-title"</span>&gt;</span>&#123;&#123;title&#125;&#125;<span class="tag">&lt;/<span class="name">view</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">view</span> <span class="attr">class</span>=<span class="string">"wx-popup-con"</span>&gt;</span>&#123;&#123;content&#125;&#125;<span class="tag">&lt;/<span class="name">view</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">view</span> <span class="attr">class</span>=<span class="string">"wx-popup-btn"</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">text</span> <span class="attr">class</span>=<span class="string">"btn-no"</span> <span class="attr">bindtap</span>=<span class="string">'_error'</span>&gt;</span>&#123;&#123;btn_no&#125;&#125;<span class="tag">&lt;/<span class="name">text</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">text</span> <span class="attr">class</span>=<span class="string">"btn-ok"</span> <span class="attr">bindtap</span>=<span class="string">'_success'</span>&gt;</span>&#123;&#123;btn_ok&#125;&#125;<span class="tag">&lt;/<span class="name">text</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">view</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">view</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">view</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>popup.js</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">Component(&#123;</span><br><span class="line">  options: &#123;</span><br><span class="line">    multipleSlots: <span class="literal">true</span> <span class="comment">// 在组件定义时的选项中启用多slot支持</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 组件的属性列表</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  properties: &#123;</span><br><span class="line">    title: &#123;            <span class="comment">// 属性名</span></span><br><span class="line">      type: <span class="built_in">String</span>,     <span class="comment">// 类型（必填），目前接受的类型包括：String, Number, Boolean, Object, Array, null（表示任意类型）</span></span><br><span class="line">      value: <span class="string">'标题'</span>     <span class="comment">// 属性初始值（可选），如果未指定则会根据类型选择一个</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">// 弹窗内容</span></span><br><span class="line">    content: &#123;</span><br><span class="line">      type: <span class="built_in">String</span>,</span><br><span class="line">      value: <span class="string">'内容'</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">// 弹窗取消按钮文字</span></span><br><span class="line">    btn_no: &#123;</span><br><span class="line">      type: <span class="built_in">String</span>,</span><br><span class="line">      value: <span class="string">'取消'</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">// 弹窗确认按钮文字</span></span><br><span class="line">    btn_ok: &#123;</span><br><span class="line">      type: <span class="built_in">String</span>,</span><br><span class="line">      value: <span class="string">'确定'</span></span><br><span class="line">    &#125; </span><br><span class="line">  &#125;,</span><br><span class="line"> </span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 组件的初始数据</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  data: &#123;</span><br><span class="line">    flag: <span class="literal">true</span>,</span><br><span class="line">  &#125;,</span><br><span class="line"> </span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 组件的方法列表</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  methods: &#123;</span><br><span class="line">    <span class="comment">//隐藏弹框</span></span><br><span class="line">    hidePopup: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">      <span class="keyword">this</span>.setData(&#123;</span><br><span class="line">        flag: !<span class="keyword">this</span>.data.flag</span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">//展示弹框</span></span><br><span class="line">    showPopup () &#123;</span><br><span class="line">      <span class="keyword">this</span>.setData(&#123;</span><br><span class="line">        flag: !<span class="keyword">this</span>.data.flag</span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">    * 内部私有方法建议以下划线开头</span></span><br><span class="line"><span class="comment">    * triggerEvent 用于触发事件</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">    _error () &#123;</span><br><span class="line">      <span class="comment">//触发取消回调</span></span><br><span class="line">      <span class="keyword">this</span>.triggerEvent(<span class="string">"error"</span>)</span><br><span class="line">    &#125;,</span><br><span class="line">    _success () &#123;</span><br><span class="line">      <span class="comment">//触发成功回调</span></span><br><span class="line">      <span class="keyword">this</span>.triggerEvent(<span class="string">"success"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>在首页用这个组件需要配置一下，首先建一个名为index.json的文件，里边配置”usingComponents”，就是需要引入到首页</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="string">"usingComponents"</span>: &#123;</span><br><span class="line">    <span class="string">"popup"</span>: <span class="string">"/component/popup/popup"</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>引入到首页</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--index.wxml--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">view</span> <span class="attr">class</span>=<span class="string">"container"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">view</span> <span class="attr">class</span>=<span class="string">"userinfo"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">button</span> <span class="attr">bindtap</span>=<span class="string">"showPopup"</span>&gt;</span> 点我 <span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">view</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">popup</span> <span class="attr">id</span>=<span class="string">'popup'</span> </span></span><br><span class="line"><span class="tag">      <span class="attr">title</span>=<span class="string">'小组件'</span> </span></span><br><span class="line"><span class="tag">      <span class="attr">content</span>=<span class="string">'学会了吗'</span> </span></span><br><span class="line"><span class="tag">      <span class="attr">btn_no</span>=<span class="string">'没有'</span> </span></span><br><span class="line"><span class="tag">      <span class="attr">btn_ok</span>=<span class="string">'学会了'</span></span></span><br><span class="line"><span class="tag">      <span class="attr">bind:error</span>=<span class="string">"_error"</span>  </span></span><br><span class="line"><span class="tag">      <span class="attr">bind:success</span>=<span class="string">"_success"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">popup</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">view</span>&gt;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>配置index.js操作点击事件</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">//index.js</span></span><br><span class="line"><span class="comment">//获取应用实例</span></span><br><span class="line"><span class="keyword">const</span> app = getApp()</span><br><span class="line"> </span><br><span class="line">Page(&#123;</span><br><span class="line">  onReady: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">//获得popup组件</span></span><br><span class="line">    <span class="keyword">this</span>.popup = <span class="keyword">this</span>.selectComponent(<span class="string">"#popup"</span>);</span><br><span class="line">  &#125;,</span><br><span class="line"> </span><br><span class="line">  showPopup() &#123;</span><br><span class="line">    <span class="keyword">this</span>.popup.showPopup();</span><br><span class="line">  &#125;,</span><br><span class="line"> </span><br><span class="line">  <span class="comment">//取消事件</span></span><br><span class="line">  _error() &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'你点击了取消'</span>);</span><br><span class="line">    <span class="keyword">this</span>.popup.hidePopup();</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">//确认事件</span></span><br><span class="line">  _success() &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'你点击了确定'</span>);</span><br><span class="line">    <span class="keyword">this</span>.popup.hidePopup();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2018/08/12/js-map-reduce-find-filter/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2018/08/12/wx-login/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
